import com.fasterxml.jackson.databind.ObjectMapper;

import javax.jws.WebService;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import javax.xml.transform.Result;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: YKH
 * Date: 2022-10-26
 * Time: 11:57
 */
//对应前端传来的请求格式
class Message{
   public String from;
   public String to;
   public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}
@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    ObjectMapper objectMapper = new ObjectMapper();
    //处理POST请求 ( 提交后将数据 传给后端)
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1.读取请求中的内容(JOSN格式)
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        //2.将请求保存到内存中
       // messagelist.add(message);
        save(message);
        System.out.println(message.toString());
        //3.返回保存成功的响应给客户端
        resp.setContentType("application/json;charset=utf8"); //设置返回格式
        resp.getWriter().write("{ \"ok\": 1}");

    }



    //处理GET请求 ( 加载页面时从 后端返回数据)
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //对于请求没有任何参数,所以不需要进行解析

        //设置响应的返回格式
        resp.setContentType("application/json;charset=utf8");
        //将 messagelist中的数据转换成jsom字符串, 参数可以是字符串,也可以是一个list
        List<Message> messageList = load();
        String respString = objectMapper.writeValueAsString(messageList);
        //将数据返回给客户端
        resp.getWriter().write(respString);

    }


    public List<Message> load() {
        Connection connection = null;
        PreparedStatement preparedStatement= null;
        ResultSet ret = null;
        List<Message> messageList = new ArrayList<>();
        try {
            //建立连接
            connection = DBUtil.getConnection();
            String sql = "select * from messages";
            preparedStatement = connection.prepareStatement(sql);
            ret = preparedStatement.executeQuery();
            while( ret.next()) {
                Message message = new Message();
                message.from = ret.getString("from");
                message.to = ret.getString("to");
                message.message = ret.getString("message");
                messageList.add(message);
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection,preparedStatement,ret);
        }
        return messageList;

    }

    public  void save(Message message)  {
        Connection connection = null;
        PreparedStatement preparedStatement= null;
        //2. 构建sql语句
        String sql = "insert into messages values(?,?,?)";
        try {
            //1. 和数据库建立连接
            connection = DBUtil.getConnection();
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1,message.from);
            preparedStatement.setString(2,message.to);
            preparedStatement.setString(3,message.message);
            //3. 执行sql语句
            int ret = preparedStatement.executeUpdate();
            if( ret!=1) {
                System.out.println("插入失败");
            } else {
                System.out.println("插入成功");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            //4. 释放连接
            DBUtil.close(connection,preparedStatement,null);
        }
    }
}
